using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Jabr.Logic.Exceptions.Handling;
using System.Collections;

namespace Jabr.GUI.Forms
{
    public partial class ExceptionDebugForm : AbstractExceptionForm
    {
        private ExceptionInfo m_ei;
        private List<ExceptionInfo> m_lei;
        private List<KeyValuePair<string, string>> m_lde;

        public ExceptionDebugForm()
        {
            InitializeComponent();

            m_lei = new List<ExceptionInfo>();
        }

        public override ExceptionInfo Info
        {
            get
            {
                return m_ei;
            }
            set
            {
                m_ei = value;
                this.Status.Visible = true;
                this.Split.Enabled = false;
                this.ListThread.RunWorkerAsync();
            }
        }

        private void InfoThread_DoWork(object sender, DoWorkEventArgs e)
        {
            m_lei.Clear();
            DeRecursive(m_ei);
        }
        private void InfoThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ExceptionList.Items.AddRange(m_lei.ToArray());
            this.Status.Visible = false;
            this.Split.Enabled = true;
        }
        private void ViewThread_DoWork(object sender, DoWorkEventArgs e)
        {
            m_lde = new List<KeyValuePair<string, string>>();
            Dictionary<string, string>.Enumerator en = m_lei[(int)e.Argument].Properties.GetEnumerator();
            while (en.MoveNext())
	        {
                m_lde.Add(en.Current);
	        }
        }
        private void ViewThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ExceptionBindingSource.DataSource = m_lde.ToArray();
            this.Status.Visible = false;
            this.Split.Enabled = true;
        }

        private void DeRecursive(ExceptionInfo p_ei)
        {
            m_lei.Add(p_ei);
            if (p_ei.Inner != null)
                DeRecursive((ExceptionInfo)p_ei.Inner);
        }

        private void ExceptionList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Status.Visible = true;
            this.Split.Enabled = false;
            this.ViewThread.RunWorkerAsync(ExceptionList.SelectedIndex);
        }

        private void ExceptionView_SelectionChanged(object sender, EventArgs e)
        {
            if (ExceptionView.SelectedRows.Count == 0)
            {
                ValueBox.Text = null;
            }
            else
            {
                ValueBox.Text = ExceptionView.SelectedRows[0].Cells["valueDataGridViewTextBoxColumn"].Value.ToString();
            }
        }
    }
}